package com.minelx.woods.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.minelx.woods.server.dao.ReviewerMappings;
import com.minelx.woods.server.perspective.Authenticated;
import com.minelx.woods.server.perspective.UserName;
import com.minelx.woods.server.service.ReviewService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
public class ReviewController {
	private final ReviewService reviewService;

	private final ReviewerMappings reviewerMappings;

	ReviewController(ReviewService reviewService, ReviewerMappings reviewerMappings) {
		this.reviewService = reviewService;
		this.reviewerMappings = reviewerMappings;
	}

	@Authenticated
	@PutMapping("review/{reviewId}")
	ResponseEntity<?> review(@UserName String userName, @PathVariable String reviewId, @RequestBody JSONObject option) {
		if (option.get("method").equals("approve")) {
			return reviewService.approve(reviewId, userName);
		} else if (option.get("method").equals("reject")) {
			return reviewService.reject(reviewId, userName);
		} else {
			return ResponseEntity.badRequest().body("unknown method: " + option.get("method"));
		}
	}

	@Authenticated
	@PostMapping("review")
	ResponseEntity<?> append(@UserName String userName, @RequestBody JSONObject added) {
		return reviewService.postReview(userName,
				added.getString("name"),
				reviewerMappings.id(userName).reviewers(),
				added.getJSONObject("info"));
	}

	@Authenticated
	@GetMapping("reviews/{offset}/{length}")
	ResponseEntity<?> list(@PathVariable int offset, @PathVariable int length) {
		return reviewService.list(offset, length);
	}
}

